#include "GameLevelDescriptionLoader.h"

#pragma warning(disable:4390)
#pragma warning(disable:4305)

GameLevelDescriptionLoader::GameLevelDescriptionLoader(void)
{
	this->gameLevel = new GameLevel();
}

GameLevelDescriptionLoader::~GameLevelDescriptionLoader(void)
{
	delete gameLevel;
}

void GameLevelDescriptionLoader::parseGameLevel(const Ogre::String &fileName, const Ogre::String &groupName) {
	rapidxml::xml_document<> XMLDoc;
	rapidxml::xml_node<>* XMLRoot;

	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(fileName, groupName);
    char* level = strdup(stream->getAsString().c_str());
    XMLDoc.parse<0>(level);

	XMLRoot = XMLDoc.first_node("game-level");

	processGameLevel(XMLRoot);
}

void GameLevelDescriptionLoader::processGameLevel(rapidxml::xml_node<>* XMLRoot) {
	rapidxml::xml_node<>* pElement;

	pElement = XMLRoot->first_node("level");
    if(pElement)
        processLevel(pElement);

	pElement = XMLRoot->first_node("sublevel");
    if(pElement)
		processSublevel(pElement);

	pElement = XMLRoot->first_node("scene");
    if(pElement)
        processSceneFile(pElement);

	rapidxml::xml_node<>* pCharElement;
	pElement = XMLRoot->first_node("chars");
    if(pElement)
    {
        pCharElement = pElement->first_node("char");
        while(pCharElement)
        {
            processCharacterEnable(pCharElement);
            pCharElement = pCharElement->next_sibling("char");
        }
    }

	pElement = XMLRoot->first_node("enemies");
    if(pElement)
        processEnemies(pElement);
}

void GameLevelDescriptionLoader::processLevel(rapidxml::xml_node<> *XMLNode) {
	if (XMLNode->value())
		this->gameLevel->level = Ogre::StringConverter::parseInt(XMLNode->value());
}

void GameLevelDescriptionLoader::processSublevel(rapidxml::xml_node<> *XMLNode) {
	if (XMLNode->value())
		this->gameLevel->sublevel = Ogre::StringConverter::parseInt(XMLNode->value());
}

void GameLevelDescriptionLoader::processSceneFile(rapidxml::xml_node<> *XMLNode) {
	if (XMLNode->value())
		this->gameLevel->fileScene = XMLNode->value();
}

void GameLevelDescriptionLoader::processCharacterEnable(rapidxml::xml_node<> *XMLNode) {
	if (XMLNode->first_attribute("id") && XMLNode->value()) {
		int charId = XMLCommonLoader::getAttribInt(XMLNode, "id");
		bool flag = XMLCommonLoader::getAttribBool(XMLNode, "enable");

		this->gameLevel->charactersEnable[charId] = flag;
	}
}

void GameLevelDescriptionLoader::processEnemies(rapidxml::xml_node<> *XMLNode) {
	if (XMLNode->first_attribute("count"))
		this->gameLevel->enemyCount = XMLCommonLoader::getAttribInt(XMLNode, "count");
}